package main

import (
	"fmt"
	"sort"
)

//#link: https://leetcode-cn.com/problems/group-anagrams-lcci/
func main() {
	strs := []string{"eat", "tea", "tan", "ate", "nat", "bat"}
	fmt.Println(groupAnagrams(strs))
}

//对每个单词按照字符顺序进行排序
//用map去存储排好序后的单词
func groupAnagrams(strs []string) [][]string {
	tempMap := make(map[string][]int)
	for i, str := range strs {
		sBytes := []byte(str)
		sort.Slice(sBytes, func(i, j int) bool {
			return sBytes[i] < sBytes[j]
		})
		tempMap[string(sBytes)] = append(tempMap[string(sBytes)], i)
	}

	result := make([][]string, 0)
	for _, value := range tempMap {
		tempStr := make([]string, 0)
		for _, index := range value {
			tempStr = append(tempStr, strs[index])
		}
		result = append(result, tempStr)
	}
	return result
}
